package jmu.edu.yjc.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import jmu.edu.yjc.Utils.PathUtils;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.enums.AppHttpCodeEnum;
import jmu.edu.yjc.exception.SystemException;
import jmu.edu.yjc.service.UpLoadService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service("upLoadService")
@ConfigurationProperties(prefix = "oss")
@Data
public class UpLoadServiceImpl implements UpLoadService {
    private String accessKey;
    private String secretKey;
    private String bucket;
    @Override
    public ResponseResult uploadImg(MultipartFile img) throws IOException {
        //判断文件类型或文件大小
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名判断
        if(!originalFilename.endsWith(".png")
                &&!originalFilename.endsWith(".jpg")
                &&!originalFilename.endsWith(".jpeg")
                &&!originalFilename.endsWith(".gif")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //如果判断通过上传到oss
        String filePath = PathUtils.generateFilePath(img,originalFilename);
        String url = upLoadOss(img,filePath);
        return ResponseResult.okResult(url);
    }

    @Override
    public ResponseResult uploadFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if(originalFilename == null){
            ResponseResult.errorResult(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        String filePath = PathUtils.generateFilePath(file,originalFilename);
        String url = upLoadOss(file,filePath);
        return ResponseResult.okResult(url);
    }


    private String upLoadOss(MultipartFile img, String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = img.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://csams.qinghui.love/"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                    ex2.printStackTrace();
                }
            }
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return "http://csams.qinghui.love/"+key;
    }
}
